package lc20240620;

public class GetIndex {
    public static void main(String[] args) {

        int[] nums = {5, 7, 8, 8, 10};
        int[] ints = new GetIndex().searchRange(nums, 8);
        for (int anInt : ints) {
            System.out.println(anInt);
        }

    }

    public int[] searchRange(int[] nums, int target) {
        int[] res = new int[2];
        res[0] = findStartIndex(nums, target);
        res[1] = findEndIndex(nums, target);
        return res;
    }

    private int findStartIndex(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int index=-1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (target <= nums[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
            if (target == nums[mid]) {
                index=mid;
            }
        }
        return index;
    }

    private int findEndIndex(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int index=-1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (target >= nums[mid]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
            if (target == nums[mid]) {
                index=mid;
            }
        }
        return index;
    }
}
